package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import exceptions.DMSServerException;

public class DMSServer {
	private int port;
	private ServerSocket ss;
	private List<DMSServerThread> list = new ArrayList<DMSServerThread>();
	public DMSServer(int port) {
		this.port=port;
	}
	public void initSocket() throws DMSServerException{
		try {
			ss = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
			throw new DMSServerException(e);
		}
	}
	
	public void startService() throws DMSServerException{
		final ExecutorService pool = Executors.newCachedThreadPool();
		Runnable r = new Runnable(){
			public void run() {
				try {
					while(true){//while(!end)
						Socket s = ss.accept();
						DMSServerThread t = new DMSServerThread(s,list);//可以多传几个参数，filelogwriter,list
						pool.execute(t);
					}
				} catch (IOException e) {
					e.printStackTrace();
//					throw new DMSServerException(e);
				}
			}
		};
		pool.execute(r);
	}
	
	public void shutDown() throws  DMSServerException{
		try {
			for (Iterator iter = list.iterator(); iter.hasNext();) {
				DMSServerThread t = (DMSServerThread) iter.next();
				iter.remove();
				if(t.s.isConnected()){
					t.s.close();
				}
			}
			ss.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new DMSServerException(e);
		}
	}
	
	public static void main(String[] args) throws DMSServerException {
		DMSServer server = new DMSServer(8001);
		server.initSocket();
		server.startService();
//		server.shutDown();
	}
}
